package com.tfjybj.itoo.exam.provider.service.impl;

import org.apache.dubbo.config.annotation.Reference;;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dmsdbj.itoo.tool.base.service.impl.BaseServicePlusImpl;
import com.google.common.collect.Lists;
import com.tfjybj.itoo.exam.entity.*;
import com.tfjybj.itoo.exam.model.*;
import com.tfjybj.itoo.exam.provider.dao.ExaminationDao;
import com.tfjybj.itoo.exam.provider.dao.ExamineeDao;
import com.tfjybj.itoo.exam.provider.dao.PaperRecordDao;
import com.tfjybj.itoo.exam.provider.dao.StudentScoreDao;
import com.tfjybj.itoo.exam.provider.service.CourseScheduleService;
import com.tfjybj.itoo.exam.provider.service.PracticeStudentService;
import com.tfjybj.itoo.exam.provider.service.StudentScoreService;
import com.tfjybj.itoo.exam.provider.service.TemplateService;
import com.tfjybj.itoo.teach.FacadeApi.CourseApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**

 * @Author: 王雪芬
 * @Description: 随堂小练学生端
 * @Date: Created in 9:09 2019/1/27
 */
@SuppressWarnings({"ALL", "unchecked"})
@Service("PracticeStudentService")
@Slf4j

public class PracticeStudentServiceImpl extends BaseServicePlusImpl<ExaminationDao, ExaminationEntity> implements PracticeStudentService {
    @Resource
    private ExaminationDao examinationDao;
    @Resource
    private StudentScoreDao studentScoreDao;
    @Resource
    private PaperRecordDao paperRecordDao;
   @Resource
   private CourseScheduleService courseScheduleService;
    @Resource
    private ExamineeDao examineeDao;
//    @Resource
//    private CourseService courseService;
    @Reference(check = false)
    private CourseApi courseApi;
    @Resource
    private StudentScoreService studentScoreService;
    @Resource
    private TemplateService templateService;

    /**
     * 根据学生学号查询实习系统正在进行的考试（小练）
     * @author 谷海涛
     * @since 2019年7月7日21:07:35
     * @param studentCode
     * @return
     */
    @Override
    public List<ExamineeModel> selectLittlePractice(String studentCode){ return examineeDao.selectLittlePractice(studentCode);}

    /**
     * 根据学生id查询正在进行的考试（小练）
     * @author 于云秀
     * @since 2019年1月27日11:43:35
     * @param userId
     * @return
     */
    @Override
   public List<ExaminationModel> selectNowExam(String userId){
        return examinationDao.selectNowExam(userId);
    }

    /**
     * 根据学生学号，考试类型和考试状态查询学号对应的课程名称、考试名称、考试成绩
     *
     * @param studentCode
     * @param examType
     * @param examState
     * @return
     * @author 杨月娥-2019年1月27日
     */
    @Override
    public Map<String,List<StudentScoreLittlePracticeModel>> selectStudentScoreByStudentIdExam(String studentId, int examType, int examState) {

        List<StudentScoreLittlePracticeModel> littlePracticeModelList = studentScoreDao.selectStudentScoreByStudentIdExam(studentId, examType, examState);
        Map<String,List<StudentScoreLittlePracticeModel>> map = littlePracticeModelList.stream().collect(Collectors.groupingBy(StudentScoreLittlePracticeModel::getCourseName));
        return map;
    }

    /**
     * 根据考生ID和考场ID和判分状态查询对应的题型名称和题干
     * @param examineeId
     * @param examinationId
     * @author 杨月娥-2019年1月27日
     * @return
     */
    @Override
    public Map<String,List<PaperRecordModel>> selectExamQuestionTypeAndQuestionContent(String examineeId, String examinationId) {
        List<PaperRecordModel>  paperRecordModelList = studentScoreDao.selectExamQuestionTypeAndQuestionContent(examineeId,examinationId);
        Map<String,List<PaperRecordModel>> map = new HashMap<>();
        Map<String,List<PaperRecordModel>> papermodelMap = paperRecordModelList.stream().collect(Collectors.groupingBy(PaperRecordModel::getQuestionTypeName));
        return papermodelMap;
    }

    @Override
    public Map<String, List<ExaminationModel>> selectNowExamQuestion(String userId) {
        List<ExaminationModel> examinationModelList = selectNowExam(userId);
        if(examinationModelList==null){
            log.warn("目前没有答题,userId-{}",userId);
            return null;
        }
        //判断coursename不可以为空
        Map<String, List<ExaminationModel>> ExaminationMapList= new HashMap<>();
        Map<String,List<ExaminationModel>> partsMap = examinationModelList.stream().collect(Collectors.toMap(ExaminationModel::getCourseName, part ->
                Lists.newArrayList(part),(List<ExaminationModel> newValueList, List<ExaminationModel> oldValueList)->
        {oldValueList.addAll(newValueList);
            return oldValueList;
        }));
        return partsMap;
    }



    /**
     * 根据学生学号查询实习系统正在进行的考试（小练）
     * @author 谷海涛
     * @since 2019年7月18日21:07:35
     * @param studentCode
     * @return
     */

    @Override
    public Map<String, List<ExaminationModel>> queryPracticeNowExamQuestion(String studentCode) {
        List<ExaminationModel> examinationModelListPra = examinationDao.queryPracticeNowExamQuestion(studentCode);
        if (examinationModelListPra == null) {
            log.warn("目前没有答题,studentCode-{}", studentCode);
            return null;
        }

        // @Override
        //public List<ExaminationModel> queryPracticeNowExamQuestion(String studentCode) {
        //return examinationDao.queryPracticeNowExamQuestion(studentCode);
        // }
        //判断coursename不可以为空
            Map<String, List<ExaminationModel>> ExaminationMapList= new HashMap<>();
            Map<String,List<ExaminationModel>> partsMap = examinationModelListPra.stream().collect(Collectors.toMap(ExaminationModel::getCourseName, part ->
                    Lists.newArrayList(part),(List<ExaminationModel> newValueList, List<ExaminationModel> oldValueList)->
            {oldValueList.addAll(newValueList);
                return oldValueList;
            }));
            return partsMap;
    }

    @Override
    public Map<String, List<PracticeTeacherModel>> selectStudentScoreBystudentId(String studentId, int examType, int examState) {
        List<PracticeTeacherModel> practiceTeacherModelList = examinationDao.selectStudentScoreBystudentId(studentId,examType,examState);
        List<StudentScoreLittlePracticeModel> studModelList=new ArrayList<>();
        for (PracticeTeacherModel practiceTeacherModel: practiceTeacherModelList) {
           StudentScoreLittlePracticeModel studentScoreLittlePracticeModel = paperRecordDao.selectPaperRecordByexaminee(practiceTeacherModel.getExamineeId());
            if (studentScoreLittlePracticeModel == null){
                StudentScoreLittlePracticeModel studentScoreLittlePracticeModel1 = new StudentScoreLittlePracticeModel();
                studentScoreLittlePracticeModel1.setStudentAnswerTotal("0");
                studentScoreLittlePracticeModel1.setStudentScore("0");
                practiceTeacherModel.setStudentScoreLittlePracticeModel(studentScoreLittlePracticeModel1);
            }else{
                practiceTeacherModel.setStudentScoreLittlePracticeModel(studentScoreLittlePracticeModel);
            }

        }
        Map<String, List<PracticeTeacherModel>> listMap = practiceTeacherModelList.stream().collect(Collectors.groupingBy(PracticeTeacherModel::getCourseName));
       //  PracticeTeacherModel ppp = new PracticeTeacherModel();
        return listMap;
    }


    /**
     * 改状态汇总成绩（小练）
     * @author 谷海涛
     * @since 2019年7月18日21:07:35
     * @param studentCode
     * @return
     */
    @Override
    @Transactional(rollbackOn = Exception.class)
    public boolean sumExamIdScore(String examineeId, String examinationId) {
        ExamineeEntity examineeEntity = examineeDao.selectById(examineeId);
        if(examineeEntity == null){
            log.warn("考生交卷汇总该考生成绩 examineeEntity is null, examineeId-{},examinationId-{}",examineeId,examinationId);
            return false;
        }
        ExaminationEntity examinationEntity = examinationDao.selectById(examinationId);

        if(examinationEntity == null){
            log.warn("考生交卷汇总该考生成绩 examinationEntity is null, examineeId-{},examinationId-{}",examineeId,examinationId);
            return false;
        }
        com.tfjybj.itoo.teach.entity.CourseEntity courseEntity = courseApi.findCourse(examinationEntity.getCourseId());
        if(courseEntity == null){
            log.warn("考生交卷汇总该考生成绩 CourseName is null, examineeId-{},examinationId-{}",examineeId,examinationId);
//            courseEntity = new CourseEntity();
            courseEntity.setName("错误数据");
        }
        ExamineeTotalScoreModel examineeTotalScoreModel= paperRecordDao.selectExameeScoreSum(examineeId,examinationId);
       List<PaperRecordEntity>  PaperRecordAnswerRightList = paperRecordDao.selectExameeAnswerRight(examineeId,examinationId);
       //查询出学生分数与标准分数一致题
        if (PaperRecordAnswerRightList != null && PaperRecordAnswerRightList.size()>0) {
            List<PaperRecordEntity> paperRecordEntities = PaperRecordAnswerRightList.stream().filter((paperRecordEntity -> paperRecordEntity.getScore().equals(paperRecordEntity.getStandardScore()))).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(paperRecordEntities)&& paperRecordEntities.size()>0 ){
                 examineeTotalScoreModel.setAnswerRightNumber(paperRecordEntities.size());
            }else {
                //总共答对题个数为空
                examineeTotalScoreModel.setAnswerRightNumber(0);
            }
        }

        TemplateEntity templateEntity = templateService.getById(examinationEntity.getTemplateId());
        if (examineeTotalScoreModel == null) {
            log.warn("考生交卷汇总该考生成绩 examineeTotalScoreModel is null, examineeId-{},examinationId-{}",examineeId,examinationId);
            return false;
        }
        if (templateEntity == null) {
            log.warn("考生交卷汇总该考生成绩 templateEntity is null, examineeId-{},examinationId-{}",examineeId,examinationId);
            return false;
        }
        StudentScoreEntity studentScoreEntity = new StudentScoreEntity();
        StudentScoreEntity stuScoreEntity = new StudentScoreEntity();
        stuScoreEntity.setExamineeId(examineeTotalScoreModel.getExamineeId());
        stuScoreEntity.setExaminationId(examineeTotalScoreModel.getExaminationId());
        Wrapper<StudentScoreEntity> wrapper = new QueryWrapper(stuScoreEntity);
        List<StudentScoreEntity> studentScoreEntities = studentScoreService.list(wrapper);
        if(CollectionUtils.isEmpty(studentScoreEntities)&&studentScoreEntities.size()==0){
            StudentScoreEntity studentScoreEntity1= new StudentScoreEntity();
            studentScoreEntity.setStudentCode(examineeEntity.getStudentCode());
            studentScoreEntity.setStudentName(examineeEntity.getStudentName());
            studentScoreEntity.setStudentScore(examineeTotalScoreModel.getTotalScore());
            studentScoreEntity.setExamineeId(examineeTotalScoreModel.getExamineeId());
            studentScoreEntity.setFullScore(examinationEntity.getScore());
            studentScoreEntity.setClassId(examineeEntity.getClassId());
            studentScoreEntity.setClassName(examineeEntity.getClassName());
            studentScoreEntity.setMajorId(examineeEntity.getMajorId());
            studentScoreEntity.setMajorName(examineeEntity.getMajorName());
            studentScoreEntity.setCourseId(examinationEntity.getCourseId());
            studentScoreEntity.setCourseName(courseEntity.getName());
            studentScoreEntity.setExaminationId(examinationId);
            studentScoreEntity.setExamClassifyId(examinationEntity.getExamClassifyId());
            studentScoreEntity.setTemplateId(examinationEntity.getTemplateId());
            studentScoreEntity.setTemplateName(templateEntity.getName());
            studentScoreEntity.setIsDelete(0);
            //小题总个数
            studentScoreEntity.setTotalQuestionCount(templateEntity.getTotalNumber());
            //表示随堂小练
            studentScoreEntity.setExamType(1);
            //答对题个数
            studentScoreEntity.setRightQuestionCount(examineeTotalScoreModel.getAnswerRightNumber());
            studentScoreService.save(studentScoreEntity);
            List<PaperRecordEntity> paperRecordEntityList = paperRecordDao.queryLikeExamineeId(examineeId);
            if(CollectionUtils.isEmpty(paperRecordEntityList)){
                log.warn("随堂小练,单个学生汇总成绩失败 examineeId-{}",examineeId);
                return false;
            }
            for (PaperRecordEntity paperRecordEntity : paperRecordEntityList) {
                 paperRecordEntity.setMarkStatus(2);
                 paperRecordDao.updateById(paperRecordEntity);
            }
            return true;
        }
        log.warn("考生成绩已经汇总,无需汇总 examineeId-{},examinationId-{}",examineeId,examinationId);
        return true;
    }

    /**
     * 不改状态汇总成绩（小练）
     * @author 谷海涛
     * @since 2019年7月18日21:07:35
     * @param studentCode
     * @return
     */
    @Override
    @Transactional(rollbackOn = Exception.class)
    public boolean sumExamIdScorePra(String examineeId, String examinationId) {
        ExamineeEntity examineeEntity = examineeDao.selectById(examineeId);
        if(examineeEntity == null){
            log.warn("考生交卷汇总该考生成绩 examineeEntity is null, examineeId-{},examinationId-{}",examineeId,examinationId);
            return false;
        }
        ExaminationEntity examinationEntity = examinationDao.selectById(examinationId);

        if(examinationEntity == null){
            log.warn("考生交卷汇总该考生成绩 examinationEntity is null, examineeId-{},examinationId-{}",examineeId,examinationId);
            return false;
        }
        com.tfjybj.itoo.teach.entity.CourseEntity courseEntity = courseApi.findCourse(examinationEntity.getCourseId());
        if(courseEntity == null){
            log.warn("考生交卷汇总该考生成绩 CourseName is null, examineeId-{},examinationId-{}",examineeId,examinationId);
//            courseEntity = new CourseEntity();
            courseEntity.setName("错误数据");
        }
        ExamineeTotalScoreModel examineeTotalScoreModel= paperRecordDao.selectExameeScoreSumPra(examineeId,examinationId);
        List<PaperRecordEntity>  PaperRecordAnswerRightList = paperRecordDao.selectExameeAnswerRightPra(examineeId,examinationId);
        //查询出学生分数与标准分数一致题
        if (PaperRecordAnswerRightList != null && PaperRecordAnswerRightList.size()>0) {
            List<PaperRecordEntity> paperRecordEntities = PaperRecordAnswerRightList.stream().filter((paperRecordEntity -> paperRecordEntity.getScore().equals(paperRecordEntity.getStandardScore()))).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(paperRecordEntities)&& paperRecordEntities.size()>0 ){
                examineeTotalScoreModel.setAnswerRightNumber(paperRecordEntities.size());
            }else {
                //总共答对题个数为空
                examineeTotalScoreModel.setAnswerRightNumber(0);
            }
        }

        TemplateEntity templateEntity = templateService.getById(examinationEntity.getTemplateId());
        if (examineeTotalScoreModel == null) {
            log.warn("考生交卷汇总该考生成绩 examineeTotalScoreModel is null, examineeId-{},examinationId-{}",examineeId,examinationId);
            return false;
        }
        if (templateEntity == null) {
            log.warn("考生交卷汇总该考生成绩 templateEntity is null, examineeId-{},examinationId-{}",examineeId,examinationId);
            return false;
        }
        StudentScoreEntity studentScoreEntity = new StudentScoreEntity();
        StudentScoreEntity stuScoreEntity = new StudentScoreEntity();
        stuScoreEntity.setExamineeId(examineeTotalScoreModel.getExamineeId());
        stuScoreEntity.setExaminationId(examineeTotalScoreModel.getExaminationId());
        Wrapper<StudentScoreEntity> wrapper = new QueryWrapper(stuScoreEntity);
        List<StudentScoreEntity> studentScoreEntities = studentScoreService.list(wrapper);
        if(CollectionUtils.isEmpty(studentScoreEntities)&&studentScoreEntities.size()==0){
            StudentScoreEntity studentScoreEntity1= new StudentScoreEntity();
            studentScoreEntity.setStudentCode(examineeEntity.getStudentCode());
            studentScoreEntity.setStudentName(examineeEntity.getStudentName());
            studentScoreEntity.setStudentScore(examineeTotalScoreModel.getTotalScore());
            studentScoreEntity.setExamineeId(examineeTotalScoreModel.getExamineeId());
            studentScoreEntity.setFullScore(examinationEntity.getScore());
            studentScoreEntity.setClassId(examineeEntity.getClassId());
            studentScoreEntity.setClassName(examineeEntity.getClassName());
            studentScoreEntity.setMajorId(examineeEntity.getMajorId());
            studentScoreEntity.setMajorName(examineeEntity.getMajorName());
            studentScoreEntity.setCourseId(examinationEntity.getCourseId());
            studentScoreEntity.setCourseName(courseEntity.getName());
            studentScoreEntity.setExaminationId(examinationId);
            studentScoreEntity.setExamClassifyId(examinationEntity.getExamClassifyId());
            studentScoreEntity.setTemplateId(examinationEntity.getTemplateId());
            studentScoreEntity.setTemplateName(templateEntity.getName());
            studentScoreEntity.setIsDelete(0);
            //小题总个数
            studentScoreEntity.setTotalQuestionCount(templateEntity.getTotalNumber());
            //表示随堂小练
            studentScoreEntity.setExamType(1);
            //答对题个数
            studentScoreEntity.setRightQuestionCount(examineeTotalScoreModel.getAnswerRightNumber());
            studentScoreService.save(studentScoreEntity);
            List<PaperRecordEntity> paperRecordEntityList = paperRecordDao.queryLikeExamineeId(examineeId);
            if(CollectionUtils.isEmpty(paperRecordEntityList)){
                log.warn("随堂小练,单个学生汇总成绩失败 examineeId-{}",examineeId);
                return false;
            }
            for (PaperRecordEntity paperRecordEntity : paperRecordEntityList) {
                paperRecordEntity.setMarkStatus(2);
                paperRecordDao.updateById(paperRecordEntity);
            }
            return true;
        }
        log.warn("考生成绩已经汇总,无需汇总 examineeId-{},examinationId-{}",examineeId,examinationId);
        return true;
    }

    @Override
    public boolean getExamineeStatus(String examineeId , String examinationId) {
        ExamineeEntity examineeEntity = examineeDao.selectById(examineeId);
        if(examineeEntity==null){
            //防止强制性交卷
            log.warn("查询考生状态examineeEntity is null ,examineeId-{}",examineeId);
            return false;
        }
        if(examineeEntity.getStudentExamState()==3){
            //交卷
            return true;
        }
        ExaminationEntity examinationEntity = examinationDao.selectById(examinationId);
        if(examinationEntity==null){
            //防止强制性交卷
            log.warn("查询考生状态examinationEntity is null ,examineeId-{}",examineeId);
            return false;
        }
        if(examinationEntity.getState()==2 || examinationEntity.getState()==3){
            //交卷
            return true;
        }
        return false;
    }

    /**
     * 根据学号查询所有成绩，实习系统（小练）
     * @author 谷海涛
     * @since 2019年7月24日11:32:30
     * @param studentCode
     * @return
     */
    @Override
    public Map<String, List<StudentScoreLittlePracticeModel>> selectStudentScoreByStudentCode(String studentCode) {
        List<StudentScoreLittlePracticeModel> littlePracticeModelList = studentScoreDao.selectStudentScoreByStudentCode(studentCode);
       Map<String,List<StudentScoreLittlePracticeModel>> map = littlePracticeModelList.stream().collect(Collectors.groupingBy(StudentScoreLittlePracticeModel::getStudentScore));
        return map;
    }

}

































